<?php
namespace app\crm\model;
use think\Model;
use think\model\concern\SoftDelete;

class CrmUser extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;
    protected $autoWriteTimestamp = true;
    
    protected $globalScope = ['shop_id'];
    public function scopeShop_id($query)
    {
        $query->where('shop_id', ShopId());
    }
    
    //关联保存客服人员信息
    static function update_user($param,$customer_id) {
        //循环
        foreach ($param['type_id'] as $k=>$r){
            //查询数据
            $data = self::where([
                'customer_id' => $customer_id,
                'type_id'     => $param['type_id'][$k],
                'user_id'     => $param['user_id'][$k]
            ])->find();
            //没找到数据,并且用户不为空
            if(!$data and $param['user_id'][$k] <> ''){
                //把旧的关联数据状态变成停用
                self::where(['type_id'=>$param['type_id'][$k],'customer_id'=>$customer_id])->update(['status'=>0]);
                //添加新的关联数据
                self::create(['shop_id'=> ShopId(),'customer_id' => $customer_id,'type_id'=>$param['type_id'][$k],'user_id'=>$param['user_id'][$k]]);
            //没找到数据,并且用户为空
            }elseif(!$data and $param['user_id'][$k] == ''){
                //把旧的关联数据状态变成停用
                self::where(['type_id'=>$param['type_id'][$k],'customer_id'=>$customer_id])->update(['status'=>0]);
            //有数据,但是状态是停用
            }elseif($data and $data['status'] == '0'){
                //把旧的关联数据状态变成停用
                self::where(['type_id'=>$param['type_id'][$k],'customer_id'=>$customer_id])->update(['status'=>0]);
                //把数据状态变成启用
                self::where(['customer_id'=>$customer_id,'type_id'=>$param['type_id'][$k],'user_id'=>$param['user_id'][$k]])->update(['status'=>1]);
            }
        }
        return true;
    }
    //关联用户
    public function user()
    {
        return $this->belongsTo(\app\user\model\User::class, 'user_id', 'id')->bind(['user_name'=>'name']);
    }
    
    //关联分类
    public function type()
    {
        return $this->belongsTo(\app\user\model\DictData::class, 'type_id', 'id')->bind(['type_name'=>'name']);
    }
    
    
}